<?php

class Purposes extends Wp_purposes_model {

    function __construct() {
        parent::__construct();
    }
    
    function getList($filter = array()) {
        $purposes = new Purposes();
        if(isset($filter['name']) && $filter['name']) {
            $purposes->addWhere("wp_purposes.name LIKE '%".$filter['name']."%'");
        }
        $purposes->orderBy("wp_purposes.name");
        $purposes->find();
        
        return $purposes;            
    }
    
    function isDeleteAble() {
        $ship_plan = new ShipPlan();
        $ship_plan->addWhere("id_wp_purposes = ".$this->id);
        return ($ship_plan->countRows()>0)?false:true;
    }

    function validateInput() {

        if (empty ($this->name)) {
            MessageHandler::add (_MSG_NAME_NOT_EMPTY, MSG_ERROR, LOG_ONLY);
        }
        
        if (strlen($this->name) > MAX_LENGTH_NAME) {
            MessageHandler::add (_MSG_PORT_NAME_IS_TOO_LONG, MSG_ERROR, LOG_ONLY);
        }
        
        if (self::isExistsByName($this->name,$this->id)) {
            MessageHandler::add (_MSG_PORT_NAME_EXISTS, MSG_ERROR, LOG_ONLY);
        }
     
        return MessageHandler::countError() > 0 ? false : true;

    }
    
    public function insert() {
        $this->created_date = date('y-m-d H:i:s');
        parent::insert();
    }
    
    public function isExistsByName($name = '', $id = 0)
	{
		if ($name == '')
		{
			return false;
		}	
		$purposes = new Purposes();
		
        if ($id) {
			$purposes->addWhere("id <> {$id}");
		}
                
        $purposes->addWhere("name = '$name'");
        $purposes->find();
		return ($purposes->countRows() > 0)?'1':'0';
	}
    
    public function isExistsByIds($ids = array())
	{
		if (!is_array($ids)) {
            return true;
        }
        
		$purposes = new Purposes();
		$purposes->addWhere("id IN (".  implode(',', $ids).")");
		$purposes->addWhere("is_deleted = ".IS_NOT_DELETED);
        $purposes->find();
		return ($purposes->countRows() == count($ids))?true:false;
	}
}
